package com.css.project.css.genCss.controller;

import com.css.common.core.text.Convert;
import com.css.framework.aspectj.lang.annotation.Log;
import com.css.framework.aspectj.lang.enums.BusinessType;
import com.css.framework.web.controller.BaseController;
import com.css.framework.web.domain.AjaxResult;
import com.css.project.css.genCss.service.IGenCssTableService;
import com.css.project.tool.gen.service.IGenTableColumnService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成 操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/css/genCss")
public class GenCssController extends BaseController
{
    @Autowired
    private IGenCssTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    /**
     * 生成代码
     */
    @PreAuthorize("@ss.hasPermi('css:genCss:code')")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/genCode/{tableName}")
    public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
    {
        byte[] data = genTableService.generatorCode(tableName);
        genCode(response, data);
    }

    /**
     * 批量生成代码
     */
    @PreAuthorize("@ss.hasPermi('css:genCss:code')")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException
    {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.generatorCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }


    /**
     * 预览代码-for-springmvc中软框架
     */
    @PreAuthorize("@ss.hasPermi('css:genCss:preview')")
    @GetMapping("/previewCss/{tableId}")
    public AjaxResult previewCSS(@PathVariable("tableId") Long tableId) throws IOException
    {
        Map<String, String> dataMap = genTableService.previewCodeCss(tableId);
        return AjaxResult.success(dataMap);
    }
}